<template>
  <div class="user">
    <high-search :list="searchList" title="用户筛选查询" @searchFn="searchFn" />
    <custom-table
      style="margin-top: 10px"
      class="custom-table"
      :column="column"
      title="用户列表"
      :tableConfig="tableConfig"
      @current-change="currentChange"
      @page-change="pageChange"
    >
      <template #customTools>
        <el-col :span="24">
          <el-button type="primary" @click="addUser">新增用户</el-button>
        </el-col>
      </template>
      <template #showName="{ row }">
        <div
          :style="{
            color:
              row.showStatus === 1
                ? 'green'
                : row.showStatus === 0
                ? 'red'
                : 'grey',
          }"
        >
          {{ row.showName }}
        </div>
      </template>
      <template #actionColumn1="scope">
        <el-button
          :disabled="scope.row.showStatus === 0"
          type="primary"
          @click="updateUser(scope)"
          >修改</el-button
        >
        <el-button
          :type="scope.row.showStatus === 0 ? 'primary' : 'danger'"
          @click="deleteFn(scope)"
          >{{ scope.row.showStatus === 0 ? "解锁" : "锁定" }}</el-button
        >
        <el-button
          @click="resetPassword(scope)"
          type="danger"
          :disabled="scope.row.showStatus === 0"
          >重置密码</el-button
        >
        <el-button
          type="primary"
          :disabled="scope.row.showStatus !== 1"
          @click="roleAuth(scope)"
          >角色授权</el-button
        >
      </template>
    </custom-table>
    <el-dialog
      @close="closeFn"
      center
      width="800px"
      title="新增用户"
      :close-on-click-modal="false"
      :visible.sync="addDialog"
    >
      <el-form ref="formItem" :model="formItem" label-width="100px"
        ><el-row :gutter="10">
          <el-col :span="item.span || 12" v-for="(item, i) in list" :key="i"
            ><el-form-item
              :prop="item.prop"
              :rules="item.rules"
              :label="item.label + ':'"
            >
              <el-input
                v-if="item.prop !== 'rid' && item.prop !== 'endTime'"
                :type="item.type || ''"
                :disabled="item.prop === 'menuCode' && dialogType === 2"
                :placeholder="item.placeholder"
                v-model="formItem[item.prop]"
              ></el-input>
              <el-select
                v-else-if="item.prop === 'rid'"
                style="width: 100%"
                v-model="formItem[item.prop]"
                :placeholder="item.placeholder"
              >
                <el-option
                  v-for="item in options"
                  :key="item.key"
                  :label="item.value"
                  :value="item.rid"
                >
                </el-option>
              </el-select>
              <el-date-picker
                v-else
                style="width: 100%"
                v-model="formItem[item.prop]"
                type="date"
                placeholder="选择日期时间"
              >
              </el-date-picker> </el-form-item></el-col></el-row
      ></el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="confirm">确认</el-button>
          <el-button @click="closeFn">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      @close="closeFn1"
      center
      width="800px"
      title="修改用户信息"
      :close-on-click-modal="false"
      :visible.sync="updateDialog"
    >
      <el-form ref="formItem1" :model="formItem1" label-width="100px"
        ><el-row :gutter="10">
          <el-col :span="item.span || 12" v-for="(item, i) in list1" :key="i"
            ><el-form-item
              :prop="item.prop"
              :rules="item.rules"
              :label="item.label + ':'"
            >
              <el-input
                :disabled="item.prop === 'menuCode' && dialogType === 2"
                v-if="item.prop !== 'endTime'"
                :placeholder="item.placeholder"
                v-model="formItem1[item.prop]"
              ></el-input>
              <el-date-picker
                v-else
                style="width: 100%"
                v-model="formItem1[item.prop]"
                type="date"
                placeholder="选择日期时间"
              >
              </el-date-picker></el-form-item></el-col></el-row
      ></el-form>
      <template #footer>
        <div>
          <el-button type="primary" @click="confirm1">确认</el-button>
          <el-button @click="closeFn1">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      center
      width="800px"
      title="角色授权"
      :close-on-click-modal="false"
      :visible.sync="roleDialog"
    >
      <custom-table
        ref="customtable"
        :column="roleColumn"
        :tableConfig="roleTableConfig"
        @checkBox-change="checkBoxChange1"
      >
      </custom-table>
      <template #footer>
        <div>
          <el-button type="primary" @click="confirm2">确认</el-button>
          <el-button @click="closeFn2">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      @close="closeFn3"
      center
      width="400px"
      title="确认密码"
      :close-on-click-modal="false"
      :visible.sync="confirmPasswordDialog"
    >
      <el-input
        placeholder="请输入密码"
        type="password"
        v-model="confirmPassword"
      >
        <template slot="prepend">密码</template>
      </el-input>
      <template #footer>
        <el-button type="primary" @click="confirm3">确认</el-button>
        <el-button @click="closeFn3">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  userList,
  addUser,
  roleSelect,
  updateUser,
  rolelist,
  userRoleUpdate,
  updataUserStatus,
  resetPassword,
} from "_my/api/admin";
import dayjs from "dayjs";
export default {
  name: "userManage",
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value ?? "") {
        callback(new Error("请输入确认密码"));
      } else if (value !== this.formItem.userPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      searchList: [
        {
          label: "用户账号",
          prop: "userCode",
          type: "input",
          placeholder: "请输入用户账号",
        },
        {
          label: "用户手机",
          prop: "userPhone",
          type: "input",
          placeholder: "请输入用户手机",
        },
        {
          label: "用户邮箱",
          prop: "userEmail",
          type: "input",
          placeholder: "请输入用户邮箱",
        },
        {
          label: "用户状态",
          prop: "showStatus",
          type: "select",
          placeholder: "请选择用户状态",
          optionList: [
            {
              key: 1,
              value: "正常",
            },
            {
              key: 2,
              value: "失效",
            },
            {
              key: 0,
              value: "锁定",
            },
          ],
        },
      ],
      resetPasswordFormItem: {},
      confirmPassword: "",
      confirmPasswordDialog: false,
      options1: [
        {
          key: 1,
          value: "正常",
        },
        {
          key: 2,
          value: "失效",
        },
        {
          key: 0,
          value: "锁定",
        },
      ],
      search: {},
      roleDialog: false,
      roleColumn: [
        {
          prop: "roleCode",
          label: "角色编码",
          width: 200,
        },
        {
          prop: "roleName",
          label: "角色名称",
          width: 200,
        },

        {
          prop: "roleInfo",
          label: "角色描述",
        },
      ],
      roleTableConfig: {
        total: 0,
        useIndex: false,
        useMultiSelect: true,
        pageNo: 1,
        pageSize: 1000,
        rowKey: "rid",
        showPagination: false,
        data: [],
        selectData: [],
      },
      options: [],
      updateDialog: false,
      title: "",
      addDialog: false,
      formItem: {
        userCode: "",
        userName: "",
        userPhone: "",
        userEmail: "",
        roleName: "",
        rid: "",
        endTime: "",
        showName: "",
        userPassword: "",
        userPassword1: "",
      },
      formItem1: {
        showName: "",
        userPhone: "",
        userEmail: "",
        endTime: "",
      },
      column: [
        {
          prop: "userCode",
          label: "用户账号",
          width: "100",
        },
        {
          prop: "userName",
          width: "200",
          label: "用户姓名",
        },

        {
          prop: "userPhone",
          label: "用户手机",
          width: "200",
        },
        {
          prop: "userEmail",
          label: "用户邮箱",
          width: "200",
        },

        {
          prop: "roleName",
          label: "角色",
          width: "200",
        },
        {
          prop: "endTime",
          label: "账户失效日期",
          width: "200",
        },
        {
          prop: "showName",
          label: "用户状态",
          width: "100",
        },
      ],
      tableConfig: {
        total: 0,
        useIndex: false,
        useMultiSelect: false,
        pageSize: 10,
        pageNo: 1,
        rowKey: "uid",
        showPagination: true,
        data: [],
        actionColumns: [
          {
            label: "操作",
            slotName: "actionColumn1",
            width: 320,
          },
        ],
      },
      list1: [
        {
          label: "用户姓名",
          prop: "userName",
          rules: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        },
        {
          label: "用户手机",
          prop: "userPhone",
          rules: [
            { required: true, message: "请输入用户手机", trigger: "blur" },
          ],
        },
        {
          label: "用户邮箱",
          prop: "userEmail",
          rules: [
            { required: true, message: "用户邮箱不能为空", trigger: "blur" },
          ],
        },
        {
          label: "账户失效日期",
          prop: "endTime",
        },
      ],
      list: [
        {
          label: "用户姓名",
          prop: "userName",
          rules: [
            { required: true, message: "用户名不能为空", trigger: "blur" },
          ],
        },
        {
          label: "用户手机",
          prop: "userPhone",
          rules: [
            { required: true, message: "用户手机不能为空", trigger: "blur" },
          ],
        },
        {
          label: "用户邮箱",
          prop: "userEmail",
          rules: [
            { required: true, message: "用户邮箱不能为空", trigger: "blur" },
          ],
        },
        {
          label: "账户失效日期",
          prop: "endTime",
        },
        {
          label: "用户账号",
          prop: "userCode",
          rules: [
            { required: true, message: "用户账号不能为空", trigger: "blur" },
          ],
        },
        {
          label: "选择角色",
          prop: "rid",
          rules: [
            { required: true, message: "用户角色不能为空", trigger: "change" },
          ],
        },
        {
          label: "用户密码",
          prop: "userPassword",
          type: "password",
          rules: [
            { required: true, message: "用户密码不能为空", trigger: "blur" },
            {
              message:
                "密码长度8至16位，必须符合由数字,大写字母,小写字母,特殊符,至少其中三种类型！(例:1234@abc)",
              trigger: "blur",
              pattern:
                /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,16}$/,
            },
          ],
          span: 24,
        },
        {
          label: "确认密码",
          prop: "userPassword1",
          type: "password",
          rules: [{ required: true, validator: validatePass, trigger: "blur" }],
          span: 24,
        },
      ],
      selectList: [],
      chooseItem: {},
    };
  },
  methods: {
    deleteFn(scope) {
      if (scope.row.showStatus !== 0) {
        this.$confirm("确定要锁定吗？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            const { uid } = scope.row;
            const data = {
              uid,
              showStatus: 0,
            };
            updataUserStatus(data).then((res) => {
              if (res.data.code === 201) {
                this.getTableList();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消锁定",
            });
          });
      } else {
        this.$confirm("确定要解锁吗？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            const { uid } = scope.row;
            const data = {
              uid,
              showStatus: 1,
            };
            updataUserStatus(data).then((res) => {
              if (res.data.code === 201) {
                this.getTableList();
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消解锁",
            });
          });
      }
    },
    closeFn3() {
      this.confirmPassword = "";
      this.confirmPasswordDialog = false;
    },
    confirm3() {
      const data = {
        uid: this.resetPasswordFormItem.uid,
        userPassword: this.confirmPassword,
        ruid: JSON.parse(sessionStorage.getItem("userInfo")).uid,
      };
      resetPassword(data).then((res) => {
        if (res.data.code === 200) {
          this.closeFn3();
          this.$alert("密码：" + res.data.userPassword, "密码已重置", {
            confirmButtonText: "确定",
          });
        } else {
          this.$message({
            type: "error",
            message: res.data.message,
          });
        }
      });
    },
    resetPassword(scope) {
      this.resetPasswordFormItem = scope.row;
      this.$confirm("确定要重置密码吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.confirmPasswordDialog = true;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置密码",
          });
        });
    },
    searchFn(params) {
      this.search = params;
      this.getTableList();
    },
    resetFn() {
      this.search = {
        userCode: "",
        userPhone: "",
        userEmail: "",
        showStatus: "",
      };
    },
    roleAuth(scope) {
      this.roleDialog = true;
      this.chooseItem = scope.row;
      const list = scope.row.rid.split(",");
      this.getRolelist(list);
    },
    getRolelist(list) {
      const data = {};
      data.pageNo = this.roleTableConfig.pageNo;
      data.pageSize = 1000;
      rolelist(data).then((res) => {
        if (res.data.code === 200) {
          this.roleTableConfig.data = res.data.data.list;
          this.roleTableConfig.total = res.data.data.total;
          this.roleTableConfig.selectData = res.data.data.list.filter((item) =>
            list.includes(item.rid + "")
          );
          this.selectList = JSON.parse(
            JSON.stringify(
              res.data.data.list.filter((item) => list.includes(item.rid + ""))
            )
          );
        }
      });
    },
    closeFn1() {
      this.updateDialog = false;
      this.formItem1 = {};
      this.$refs.formItem1.resetFields();
    },
    closeFn2() {
      this.roleDialog = false;
    },
    confirm2() {
      const arr = this.selectList.map((item) => {
        const obj = {};
        obj.rid = item.rid;
        obj.status = 1;
        return obj;
      });
      this.chooseItem.rid.split(",").forEach((item) => {
        if (!arr.map((item1) => item1.rid).includes(Number(item))) {
          arr.push({
            rid: Number(item),
            status: 0,
          });
        }
      });
      if (arr.every((item) => item.status === 0)) {
        return this.$message({
          type: "error",
          message: "请至少授权一个角色",
        });
      }
      userRoleUpdate({ list: arr, uid: this.chooseItem.uid }).then((res) => {
        if (res.data.code === 201) {
          this.closeFn2();
          this.getTableList();
        }
      });
    },
    checkBoxChange1(selection, row) {
      this.selectList = selection;
      this.roleTableConfig.selectData = [];
    },
    closeFn() {
      this.addDialog = false;
      this.$refs.formItem.resetFields();
    },
    confirm() {
      this.$refs.formItem.validate((res) => {
        if (res) {
          this.formItem.endTime = this.formItem.endTime
            ? dayjs(this.formItem.endTime).format("YYYY-MM-DD")
            : "";
          addUser(this.formItem).then((res) => {
            if (res.data.code === 201) {
              this.closeFn();
              this.getTableList();
            }
          });
        } else {
          this.$message({
            type: "info",
            message: "请完成必填项",
          });
        }
      });
    },
    confirm1() {
      this.$refs.formItem1.validate((res) => {
        if (res) {
          this.formItem1.endTime = this.formItem1.endTime
            ? dayjs(this.formItem1.endTime).format("YYYY-MM-DD")
            : "";
          updateUser(this.formItem1).then((res) => {
            if (res.data.code === 201) {
              this.closeFn1();
              this.getTableList();
            }
          });
        } else {
          this.$message({
            type: "info",
            message: "请完成必填项",
          });
        }
      });
    },
    updateUser(scope) {
      this.formItem1 = JSON.parse(JSON.stringify(scope.row));
      this.updateDialog = true;
    },
    addUser() {
      this.addDialog = true;
      // this.$forceUpdate();
      this.getSelectList();
    },

    getTableList() {
      const data = Object.assign({}, this.search);
      const { pageNo, pageSize } = this.tableConfig;
      data.pageNo = pageNo;
      data.pageSize = pageSize;
      userList(data).then((res) => {
        if (res.data.code === 200) {
          this.tableConfig.data = res.data.data.list;
          this.tableConfig.total = res.data.data.total;
        }
      });
    },
    currentChange(current) {
      this.tableConfig.pageNo = current;
      this.getTableList();
    },
    pageChange(pageSize) {
      this.tableConfig.pageSize = pageSize;
      this.tableConfig.pageNo = 1;
      this.getTableList();
    },
    getSelectList() {
      roleSelect().then((res) => {
        if (res.status === 200) {
          this.options = res.data;
        }
      });
    },
  },
  mounted() {
    this.getTableList();
  },
};
</script>

<style lang="less" scoped>
.user {
  user-select: none;
  user-zoom: 0;
  -webkit-user-drag: none;
}

.search :deep(.el-form-item) {
  margin-bottom: 10px;
}
</style>
